const ACCESSTOKEN = localStorage.getItem('access_token');
const USERNAME = localStorage.getItem('userName');

if (ACCESSTOKEN && USERNAME && ACCESSTOKEN.length > 10) {
  const $startDate = $('#startDate'); // 开始时间输入框
  const $checkBoxBtns = $('.check-box-btn'); // 完成状态
  const $projectTypes = $('.project-types'); // 项目名称
  const $projectTableBody = $('.project-table tbody'); // 表格body

  let isDone = false; // 默认完成状态
  let projectType = '全部'; // 默认项目名称
  let startDate = '2017-01-01'; // 默认开始时间
  let token; // token
  let projectsList = [];
  const params = {
    count: 1000,
    page: 0,
    hasDueDate: false
  }; // 接口参数

  function exportTo(type) {
    $('.project-table').tableExport({
      filename: USERNAME + '-' + projectType,
      format: type
    });
  }

  $('.title-text').text(projectType);
  $('.top-info .user-name').text(USERNAME);

  // 列表模板
  var template = function(list, index) {
    return `<tr data-type=${list.changeColor}>
      <td class="text-center">${index}</td>
      <td>${list.parent}</td>
      <td>${list.content}</td>
      <td class="text-center">${list.updated}</td>
    </tr>`;
  };

  // 改变完成状态
  $checkBoxBtns.on('change', (event) => {
    if (event.target.value === 'false') {
      isDone = false;
    } else {
      isDone = true;
    }
  })

  // 改变项目名称
  $projectTypes.on('change', (event) => {
    const allLists = JSON.parse(JSON.stringify(projectsList));
    projectType = event.target.value;
    $('.title-text').text(projectType);

    const filterProjects = allLists.filter(item => {
      if(item.project === projectType) {
        return item;
      }
    });
    renderListView(filterProjects);
  })

  // 查询
  $('.search').on('click', (event) => {
    token = 'OAuth2 ' + $.trim(ACCESSTOKEN);
    params.isDone = isDone;
    if ($startDate.val() !== '') {
      startDate = $startDate.val();
    }
    
    params.startDate = new Date(startDate).toISOString();
    getExportLists(params, token);
  })

  // 导出选择
  $('.export').on('click', () => {
    $('.export').toggleClass('is-active');
    $('.dropdown-menu').toggleClass('is-active');
    // method2('product-table');
  })

  // 导出
  $('.dropdown-menu').on('click', () => {
    $('.export').removeClass('is-active');
    $('.dropdown-menu').removeClass('is-active');
  })


  /**
   * 获取列表数据
   * @param {Object} searchParams 搜索对象
   * @param {string} userToken 用户token
   */
  function getExportLists(searchParams, userToken) {
    $.ajax({
      method: 'GET',
      url: '/api/v2/tasks/me',
      headers: {
        'Authorization': userToken
      },
      data: searchParams,
      success(data) {
        filterLists(data);
      },
    });
  }

  /**
   * 列表排序
   * @param {Array} lists 
   */
  function filterLists(lists) {
    const projects = JSON.parse(JSON.stringify(lists));

    if(projects.length > 0) {
      const listArrs = [];

      projects.forEach(item => {
        const listArr = {};
        listArr.project = item.project.name;
        listArr.created = item.created;
        listArr.updated = item.updated.slice(0, 10);
        if(item.parent) {
          listArr.parent = item.parent.content;
          listArr.content = item.content;
        } else {
          listArr.content = '';
          listArr.parent = item.content;
        }

        listArrs.push(listArr);
      });


      // 排序
      listArrs.sort(function (a, b) {
        return (b.parent + a.created).localeCompare((a.parent + b.created));
      });

      // console.log(listArrs);
      projectsList = JSON.parse(JSON.stringify(listArrs));
      renderListView(listArrs);
    } else {
      projectsList= [];
      renderListView([]);
    }

    getProjectTypes(projectsList);
  }

  /**
   * 获取任务项目
   * @param {Array} arrs 任务数组
   */
  function getProjectTypes(arrs) {
    const typesObj = {};
    const typesObjArr = ['全部'];

    if(arrs.length <= 0) {
      $projectTypes.hide();
    } else {
      $projectTypes.show();
      arrs.forEach((item) => {
        typesObj[item.project] = item.project;
      });
    
      for (key in typesObj) {
        typesObjArr.push(key);
      }
    }

    $projectTypes.find('option').remove();
    typesObjArr.forEach((item) => {
      const itemDOMType = $(`
        <option value=${item}>${item}</option>
      `);
      $projectTypes.append(itemDOMType);
    });
  }

  /**
   * 渲染视图
   * @param {Array} lists 
   */
  function renderListView(lists) {
    $projectTableBody.find('tr').remove();
    if (lists.length > 0) {
      let isChangeColor = true;
      for(let i = 0; i < lists.length; i++) {
        lists[i].changeColor = isChangeColor;

        if (lists.length > 1) {
          if(i < (lists.length - 1)) {
            if(lists[i].parent !== lists[i + 1].parent) {
              isChangeColor = !isChangeColor;
            }
          } else {
            if(lists[i].parent !== lists[i - 1].parent) {
              isChangeColor = !isChangeColor;
            }
          }
        }

        const itemDOM = $(template(lists[i], i));
        $projectTableBody.append(itemDOM);
      }
    } else {
      const itemDOM = $(
        `<tr class="no-data">
          <td colspan="5" style="text-align: center;font-size: 16px">暂无数据！</td>
        </tr>`
      );
      $projectTableBody.append(itemDOM);
    }
  }

  /**
   * 导出代码（无插件）
   */ 
  // var idTmr;
  // function  getExplorer() {
  //   var explorer = window.navigator.userAgent;
    
  //   if (explorer.indexOf("MSIE") >= 0) {
  //     //ie 
  //     return 'ie';
  //   } else if (explorer.indexOf("Firefox") >= 0) {
  //     //firefox 
  //     return 'Firefox';
  //   } else if(explorer.indexOf("Chrome") >= 0) {
  //     //Chrome
  //     return 'Chrome';
  //   } else if(explorer.indexOf("Opera") >= 0) {
  //     //Opera
  //     return 'Opera';
  //   } else if(explorer.indexOf("Safari") >= 0) {
  //     //Safari
  //     return 'Safari';
  //   }
  // }

  // function method2(tableid) {
  //   //整个表格拷贝到EXCEL中
  //   if(getExplorer() === 'ie') {
  //     var curTbl = document.getElementById(tableid);
  //     var oXL = new ActiveXObject("Excel.Application");

  //     //创建AX对象excel 
  //     var oWB = oXL.Workbooks.Add();
  //     //获取workbook对象 
  //     var xlsheet = oWB.Worksheets(1);
  //     //激活当前sheet 
  //     var sel = document.body.createTextRange();
  //     sel.moveToElementText(curTbl);
  //     //把表格中的内容移到TextRange中 
  //     sel.select();
  //     //全选TextRange中内容 
  //     sel.execCommand("Copy");
  //     //复制TextRange中内容  
  //     xlsheet.Paste();
  //     //粘贴到活动的EXCEL中       
  //     oXL.Visible = true;
  //     //设置excel可见属性

  //     try {
  //       var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
  //     } catch (e) {
  //       print("Nested catch caught " + e);
  //     } finally {
  //       oWB.SaveAs(fname);

  //       oWB.Close(savechanges = false);
  //       //xls.visible = false;
  //       oXL.Quit();
  //       oXL = null;
  //       //结束excel进程，退出完成
  //       //window.setInterval("Cleanup();",1);
  //       idTmr = window.setInterval("Cleanup();", 1);
  //     }
  //   } else{
  //     tableToExcel(tableid);
  //   }
  // }

  // function Cleanup() {
  //     window.clearInterval(idTmr);
  //     // CollectGarbage();
  // }

  // var tableToExcel = (function() {
  //     var uri = 'data:application/vnd.ms-excel;base64,';
  //     var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
  //     var base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) };
  //     var format = function(s, c) {
  //         return s.replace(/{(\w+)}/g,
  //         function(m, p) { return c[p]; }) }
  //             return function(table, name) {
  //                 if (!table.nodeType) table = document.getElementById(table)
  //                 var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
  //                 window.location.href = uri + base64(format(template, ctx))
  //               }
  // })();
} else {
  location.href = '/';
}